<?php

namespace GordenSong\Laravel\Support;

use GordenSong\Laravel\Support\Traits\PrefixTrait;
use GordenSong\Laravel\Support\Traits\ValidatorTrait;
use GordenSong\Laravel\Utils\RuleUtil;
use Illuminate\Contracts\Support\Arrayable;
use Illuminate\Support\Traits\Macroable;

class Collection implements Arrayable
{
	use ValidatorTrait, PrefixTrait, Macroable;

	/**
	 * Collection constructor.
	 * @param Validator[]|Collection[]|array $validators
	 */
	public function __construct(array $validators)
	{
		foreach ($validators as $key => $validator) {
			if (is_numeric($key)) {
				$this->add($validator);
			} elseif (is_string($key)) {
				$this->add($validator->prefix($key));
			}
		}
	}

	/**
	 * @param Validator|Collection $validator
	 * @return $this
	 */
	public function add($validator): Collection
	{
		if (!$validator instanceof Validator && !$validator instanceof Collection) {
			throw new \InvalidArgumentException();
		}

		$this->rules = RuleUtil::mergeManyRules($this->rules(), $validator->rules());
		$this->attributes = array_merge($this->attributes(), $validator->attributes());
		$this->messages = array_merge($this->messages(), $validator->messages());

		return $this;
	}

	/**
	 * @param Validator[]|Collection[]|array $validators
	 * @return Collection
	 */
	public static function make(array $validators = []): Collection
	{
		return new static($validators);
	}

	public function toArray(): array
	{
		return [
			'rules' => $this->rules(),
			'messages' => $this->messages(),
			'attributes' => $this->attributes(),
		];
	}
}
